<?php
require_once 'include/inc.config.php';
require_once WACT_ROOT . '/db/db.inc.php';
require_once APP_ROOT.'model/common/utils.php';
require_once APP_ROOT.'model/common/session.php';
require_once APP_ROOT.'model/common/date.php';
require_once APP_ROOT.'model/common/parameters.php';
require_once APP_ROOT.'model/common/site.php';


class ArticleFilter {
    function doFilter(&$vars){
    	if($vars['published']==1) {
    		if(isset($vars['status']))
    			$status='Published (shown)';
    		else $status='Published (waiting)';
    	} else if($vars['denied']==1)
    		$status='Denied';
    		else $status='Pending';
    	$vars['status']=$status;

    	if(isset($vars['premium'])&&$vars['premium']==1){
    		$vars['prem']='1';
    	}

    	$mydate=strtotime($vars['date_added']);
        $tz =& new MyTimeZone();
        $mydate = $tz->timeGMT($mydate);
    	$dateformatted=gmstrftime('%b %d, %Y',$mydate);
    	$vars['date_added_formatted']=$dateformatted;
    }
}

class LatestArticleFilter {
	 function doFilter(&$vars){
    	$headline=$vars['headline'];
    	$premium = $vars['premium'];
        if ($premium) $vars['premium_show'] = 1;
    	$vars['fullheadline'] = $headline; // store full headline as well
    	$size=44;
    	$vars['headline'] = Article::GetShortText2($headline,$size);

	 }
  }

  class LatestHeadlinesFilter {
  		 function doFilter(&$vars) {
            $premium = $vars['premium'];
        	if ($premium) $vars['premium_show'] = 1;
            $size=200;
            $summary = $vars['summary'];
            $headline=$vars['headline'];
            $vars['summary'] = Article::GetShortText2($summary,$size);
            $vars['fullheadline'] = $headline; // store full headline as well
    		$size=24;
    		$vars['headline'] = Article::GetShortText2($headline,$size);
  		 }
  }


class Article {
	// TO DO: check that 2 categories are linked
	var $resent=array('1'=>'1 day','5'=>'5 days','7'=>'7 days','15'=>'15 days','30'=>'30 days','60'=>'60 days');

    function insertArticle(&$data) {
    	$site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);
    	$description=$data->get('description');
    	$url=Utils::findImageUrlinHTML($description);
   		$data->set('big_picture',$url);

   		$small_img=$data->get('small_picture');
   		if($small_img&&$small_img[0]=='/') {
   			$small_img=substr($small_img,1);
   			$data->set('small_picture',$small_img);
   		}
   	/*	if($small_img){
   			$small_img='http://'.$_SERVER['HTTP_HOST'].$small_img;

   		}*/
        $Record =& DBC::NewRecord($data);
        return $Record->insertId('sport_articles',
            array('headline','date_added', 'date_show', 'author_user_id', 'summary', 'description',
            'premium','teaser','category_id','category2_id','published','form_id','add_banner','small_picture','big_picture','front_picture','site_id'),
            'article_id');
    }

    function getPublicURLByID($id) {
    	$url = 'articles/details.htm?id='.$id;
    	if (APP_NAME!='.') $url = '/'.APP_NAME.'/'.$url;
    	else  $url = '/'.$url;
    	return $url;
    }

    function getIDByName($name) {
        $site_id = Site::getSiteID();
    	$rec =& DBC::FindRecord("SELECT article_id from sport_articles A where A.headline = ".DBC::makeLiteral($name)." and A.site_id = ".DBC::makeLiteral($site_id));
     	if ($rec) return $rec->get('article_id');
     	else return 0;
    }

     function getPublicURLByName($name) {
     		$id = Article::getIDByName($name);
     		$url = Article::getPublicURLByID($id);
     		return $url;
     }

    function &getRecord($id) {
        return DBC::FindRecord("SELECT A.*, U.*, C1.name as category1, C2.name as category2
        FROM sport_articles A
        left outer join sport_users U on A.author_user_id = U.user_id
        left outer join sport_categories C1 on A.category_id = C1.category_id
     	left outer join sport_categories C2 on A.category2_id = C2.category_id
        WHERE A.article_id = ". DBC::makeLiteral($id));
    }

    function updateArticle($id, &$data) {
        $site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);
    	$description=$data->get('description');
    	//print $description;
    	$url=Utils::findImageUrlinHTML($description);
   		$data->set('big_picture',$url);

   		$small_img=$data->get('small_picture');
   		if($small_img&&$small_img[0]=='/') {
   			$small_img=substr($small_img,1);
   			$data->set('small_picture',$small_img);
   		}

        $Record =& DBC::NewRecord($data);
        $Record->update('sport_articles',
            array('headline', 'date_show', 'author_user_id', 'admin_user_id', 'summary', 'description',
            'premium','teaser','category_id','category2_id','published','form_id','add_banner','small_picture','big_picture','front_picture','site_id'),
            "article_id=". DBC::makeLiteral($id));
    }

    function updateArticleWithCreationDate($id, &$data) {
        $site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);
    	$description=$data->get('description');
    	//print $description;
    	$url=Utils::findImageUrlinHTML($description);
   		$data->set('big_picture',$url);

   		$small_img=$data->get('small_picture');
   		if($small_img&&$small_img[0]=='/') {
   			$small_img=substr($small_img,1);
   			$data->set('small_picture',$small_img);
   		}

        $Record =& DBC::NewRecord($data);
        $Record->update('sport_articles',
            array('headline', 'date_show', 'date_added', 'author_user_id', 'admin_user_id', 'summary', 'description',
            'premium','teaser','category_id','category2_id','published','form_id','add_banner','small_picture','big_picture','front_picture','site_id'),
            "article_id=". DBC::makeLiteral($id));
    }

    function &getUserArticlesList(&$Pager,$user_id,$option=null) {
        $site_id = Site::getSiteID();
        $isGlobal = Site::IsGlobal();
    	$query="SELECT A.*,C.name as \"category1\",B.name as \"category2\", if(A.date_show<=now(),'true',NULL) as \"status\" ";
    	$query.="  FROM ";
    	$query.=" (sport_articles A left outer join sport_categories C on A.category_id= C.category_id) ";
    	$query.=" left outer join sport_categories B on category2_id=B.category_id ";
    	$query.=" where author_user_id=".DBC::makeLiteral($user_id).
    	" and (A.site_id = ".DBC::makeLiteral($site_id)."";
    	if ($isGlobal) $query.=" or 1=1)";
    	else $query.=") ";
    	if($option!=null) $query.=" and TO_DAYS(A.date_added)>=TO_DAYS(now())-$option";
    	//print $query;
       	return DBC::NewPagedRecordSet($query,$Pager,new ArticleFilter());
    }

    function &getResentList(){
    	$resents=array('1'=>'1 day','5'=>'5 days','7'=>'7 days','15'=>'15 days','30'=>'30 days','60'=>'60 days');

    	return $resents;
    }

    function getArticlesCount($user_id) {
        $site_id = Site::getSiteID();
        $isGlobal = Site::IsGlobal();
        $sql = "Select count(*) from sport_articles where author_user_id=".DBC::makeLiteral($user_id).
    	" and (site_id = ".DBC::makeLiteral($site_id);
    	if ($isGlobal) $sql.=" or 1=1)";
    	else $sql.=") ";
    	return DBC::getOneValue($sql);
    }

    function getNewArticlesCount() {
        $site_id = Site::getSiteID();
        //$isGlobal = Site::IsGlobal();
        $isGlobal = false;
        $sql = "Select count(*) from sport_articles where (published = 0 or published is null) and (denied=0 or denied is null)
        and (site_id = ".DBC::makeLiteral($site_id) ;
        if ($isGlobal) $sql.=" or 1=1)";
    	else $sql.=") ";
    	return DBC::getOneValue($sql);
    }

    function denyArticle($article_id) {
        $data = new DataSpace();
        $data->set('denied',1);
        $data->set('published',0);
    	$Record =& DBC::NewRecord($data);
        $Record->update('sport_articles', array('denied', 'published'),
            "article_id=". DBC::makeLiteral($article_id));
    }

    function publishArticle($article_id) {
        $data = new DataSpace();
        $data->set('denied',0);
        $data->set('published',1);
    	$Record =& DBC::NewRecord($data);
        $Record->update('sport_articles',
            array('denied', 'published'),
            "article_id=". DBC::makeLiteral($article_id));
    }

    // get the next new article
    function &getNextNewArticle($current_article_id) {
        $site_id = Site::getSiteID();
        $sql = "select A.* from sport_articles A, sport_articles A2
        where A.article_id <> A2.article_id
        and A2.article_id = ".DBC::makeLiteral($current_article_id)."
        and A.date_added <= A2.date_added
        and (A.published = 0  or  A.published is null)
        and A.site_id = ".DBC::makeLiteral($site_id)."
        and A2.site_id = ".DBC::makeLiteral($site_id)."
        order by A.date_added desc limit 1";
        return DBC::FindRecord($sql);
    }


	function delete($id) {
        DBC::execute("DELETE FROM sport_articles WHERE article_id=". DBC::makeLiteral($id));
    }

    function &getArticlesList(&$Pager, &$request, &$responseModel,$options=null, $onlynew=false) {
        $site_id = Site::getSiteID();
     	//restore filter from session
     	Session::loadResponseModel($responseModel,'filter.articles');
     	$sql = "select A.*, U.*, C1.name as category1, C2.name as category2
     		from sport_articles A
     		left outer join sport_users U on A.author_user_id = U.user_id
     		left outer join sport_categories C1 on A.category_id = C1.category_id
     		left outer join sport_categories C2 on A.category2_id = C2.category_id";

     	if($options==null){
     		if ($onlynew) {
                $sql.=" where 1=1 and (A.published=0 or A.published is null)
                and A.site_id = ".DBC::makeLiteral($site_id)."
     		 	order by A.date_added desc ";
     		} else {
     			$sql.=" where 1=1 and published=1
                and A.site_id = ".DBC::makeLiteral($site_id)." ".Article::getArticlesFilter($request, $responseModel)."
     		 	order by ".Article::getArticlesOrder($request, $responseModel);
     		}
            //print $sql;
        	return DBC::NewPagedRecordSet($sql, $Pager);
     	}else{
     		$sql.=" where published=1
             and A.site_id = ".DBC::makeLiteral($site_id)." ".Article::getPublicArticleFilter($request,$responseModel);
     		$sql.=" order by A.date_added desc,A.headline,U.firstname";
     		error_log("[SQL:]$sql");
     		return DBC::NewPagedRecordSet($sql, $Pager,new ArticleFilter());
     	}
     }

      function &getNewArticlesList(&$Pager, &$request, &$responseModel) {
      	return Article::getArticlesList($Pager, $request, $responseModel,null,true);
      }



     function &getLatestArticles($sport_id,$community_id) {
        $site_id = Site::getSiteID();
        $isGlobal = Site::IsGlobal();
     	$number = Parameters::getNumberFrontPageArticles();
     	$sql = "select A.* from sport_articles A where A.published=1 and A.date_show<=now()";
     	if($sport_id) $sql.=" and category_id=$sport_id";
     	if($community_id) $sql.=" and category2_id=$community_id ";
        $sql.=" and (A.site_id = ".DBC::makeLiteral($site_id);
        if ($isGlobal) $sql.=" or 1=1) ";
    	else $sql.=") ";
        $sql.=" and (length(A.small_picture) > 0 or 1=1)";
     	$sql.=" order by A.date_added desc limit ".$number;
     	//print  $sql;
        $rs =& DBC::NewRecordSet($sql,  new LatestHeadlinesFilter());

        //$list_updated=array();
        //$rs->reset();
        //while ($list->next()) {
        	//$dataspace = $rs->export();
        	//$article_id = $rs->get('article_id');
            //$premium = $rs->get('premium');
            //if ($premium) $dataspace['premium_show'] =  1;
            //$list_updated[$article_id] = $dataspace;
        //}

        //$list_source_updated =& new ArrayDataSet($list_updated);

        //return $list_source_updated;
        return $rs;

     }

     function &getLatestArticles2($sport_id,$community_id) {
       	$number1 = Parameters::getNumberFrontPageArticles();
        $number2 = Parameters::getNumberRecentArticles();
        $site_id = Site::getSiteID();
        $isGlobal = Site::IsGlobal();
     	$sql = "select A.* from sport_articles A where A.published=1 and A.date_show<=now()";
     	if($sport_id) $sql.=" and category_id=$sport_id";
     	if($community_id) $sql.=" and category2_id=$community_id ";
     	$sql.=" and (A.site_id = ".DBC::makeLiteral($site_id);
        if ($isGlobal) $sql.=" or 1=1) ";
    	else $sql.=") ";
     	$sql.=" order by A.date_added desc limit ".$number1.','.$number2;
        return DBC::NewRecordSet($sql, new LatestArticleFilter());

     }


     function getPublicArticleFilter(&$request,&$responseModel){
     	$where = '';
     	$recent=$responseModel->get('type_recent');
     	$tz =& new MyTimeZone();
     //	error_log("[RESENT]:$recent");
     	if($recent&&$recent==1){
     		$recentdays=$responseModel->get('recent');
     		$where.=" and TO_DAYS(A.date_added)>=TO_DAYS(now())-$recentdays";
     	}
     	else {
     		$start_day = $responseModel->get('start_day');
        	$start_month = $responseModel->get('start_month');
        	$start_year = $responseModel->get('start_year');
        	if (!$start_year) $start_year = 2005;
        	$start_date = gmmktime(0, 0, 0, $start_month, $start_day, $start_year);
        	$start_date = $tz->timeLocal( $start_date );
        	$where .= " and A.date_added>='".gmstrftime("%Y.%m.%d",$start_date)."'";
     	}

     	$category1=$responseModel->get('category1');
     	$category2=$responseModel->get('category2');

     	if($category1&&$category1>0)
     		$where.=" and A.category_id=$category1";
     	if($category2&&$category2>0)
     		$where.=" and A.category2_id=$category2";

     	$author=$responseModel->get('author');
     	if($author&&$author>0)
     		$where .= ' and A.author_user_id = '.DBC::makeLiteral($author);

     	return $where;
     }

      function getArticlesFilter(&$request,&$responseModel) {
      	$where = '';
      	$filter_article_id = $responseModel->get('filter_article_id');
        $article_id = $responseModel->get('article_id');
      	if ($filter_article_id)  $where .= ' and A.article_id = '.DBC::makeLiteral($article_id);

        $filter_headline = $responseModel->get('filter_headline');
        $headline = $responseModel->get('headline');
        if ($filter_headline)  $where .= ' and A.headline like '.DBC::makeLiteral('%'.$headline.'%').'  ';

        $filter_category1 = $responseModel->get('filter_category1');
        $category1 = $responseModel->get('category1');
        if ($filter_category1)  $where .= ' and A.category_id = '.DBC::makeLiteral($category1);

        $filter_category2 = $responseModel->get('filter_category2');
        $category2 = $responseModel->get('category2');
        if ($filter_category2)  $where .= ' and A.category2_id = '.DBC::makeLiteral($category2);

        $filter_author = $responseModel->get('filter_author');
        $author = $responseModel->get('author');
        if ($filter_author)  $where .= ' and A.author_user_id = '.DBC::makeLiteral($author);

        $filter_start_date = $responseModel->get('start_date_filter');
        $start_day = $responseModel->get('start_day');
        $start_month = $responseModel->get('start_month');
        $start_year = $responseModel->get('start_year');
        $start_date = gmmktime(0, 0, 0, $start_month, $start_day, $start_year);
        $tz =& new MyTimeZone();
        $start_date = $tz->timeLocal( $start_date );
        if ($filter_start_date) $where .= " and A.date_added>='".gmdate("Y.m.d",$start_date)."'";

        $filter_end_date = $responseModel->get('end_date_filter');
        $end_day = $responseModel->get('end_day');
        $end_month = $responseModel->get('end_month');
        $end_year = $responseModel->get('end_year');
        $end_date = gmmktime(0, 0, 0, $end_month, $end_day, $end_year);
        $end_date = $tz->timeLocal( $end_date );
        if ($filter_end_date) $where .= " and A.date_added<='".gmdate("Y.m.d",$end_date)."'";

        $filter_recent = $responseModel->get('recent_filter');
        $recent = $responseModel->get('recent');
        if ($recent) {
        	$start_date = gmmktime(0, 0, 0, gmdate("m"), gmdate("d")-$recent, gmdate("Y"));
        	$start_date = $tz->timeLocal( $start_date );
        }
        if ($filter_recent) $where .= " and A.date_added>='".gmdate("Y.m.d",$start_date)."'";


        return $where;
      }

      function getArticlesOrder(&$request,&$responseModel) {
      	$sortby = 'A.date_added desc';
      	$sortby = $responseModel->get('sort');
      	if ($sortby) return 'A.'.$sortby;
      	else return 'A.date_added desc';
      }


       function &getRecordForScrolling($sport,$community) {
        $site_id = Site::getSiteID();
        $isGlobal = Site::IsGlobal();
         //$sql.=" and A.site_id = ".DBC::makeLiteral($site_id);
      	$query="select A.* from sport_articles A where front_picture is not null and front_picture<>'' ";
      	$query.=" and published=1 and date_show<=now() ";
        $query.=" and (A.site_id = ".DBC::makeLiteral($site_id)." ";
        if ($isGlobal) $query.=" or 1=1) ";
    	else $query.=") ";
      	if($sport)
			$query.=" and category_id=$sport ";
		if($community) $query.=" and category2_id=$community ";
		$query.=" order by A.date_added desc";
		$dataset=DBC::NewRecordSet($query);
		$dataset->reset();
		if($dataset->next()) {
			$ar=$dataset->export();
			return $ar;
		}
		else{
			$ar=null;
			if ($sport && $community)     {
            	$ar = Article::getRecordForScrolling($sport,null);
            	if (!$ar) $ar = Article::getRecordForScrolling(null,$community);
                if (!$ar) $ar = Article::getRecordForScrolling(null,null);
            } else if ($sport) {
              	$ar = Article::getRecordForScrolling(null,null);
            } else if ($community) {
              	$ar = Article::getRecordForScrolling(null,null);
            }

			return $ar;
		}
      }

      function GetShortText($text, $size) {
      	$newtext = '';
        if(strlen($text)<=$size){
    		$newtext=$text;
    		if(strstr('. ,!?-',$newtext[strlen($newtext)-1])){
    			$newtext=substr($newtext,0,strlen($newtext)-2);
    		}
    		//$newtext=$newtext.'...';
    	} else {
    		$newtext=substr($text,0,$size-1);
    		if(strstr('. ,!?-',$newtext[strlen($newtext)-1])){
    			$newtext=substr($newtext,0,strlen($newtext)-2);
    			 $newtext=$newtext.'...';
    		} else{
    			$i=$size-1;
    			while(strlen($text)>$i && !strstr('. ,!?-',$text[$i])) {
    				$newtext.=$text[$i];
    				$i++;
    			}
    			$newtext=$newtext.'...';
    		}
    	}
    	return $newtext;
      }

      function GetShortText2($text, $size) {
      	$newtext = '';
        if(strlen($text)<=$size){
    		$newtext=$text;
    	} else {
      		$newtext=substr($text,0,$size-1).'...';
      	}
        return $newtext;
      }
}

?>
